//
// Created by long on 2021/11/26.
//

#ifndef SHEEPRENDER_SR_PROFILER_H
#define SHEEPRENDER_SR_PROFILER_H

namespace SR {
    struct sr_clock {
        std::string sid;
        clock_t p_clock;
        double cnt_timer;

        sr_clock(std::string sid) {
            this->sid = sid;
            p_clock = clock();
            cnt_timer = 0;
        }
    };

    // 简易计时器
    struct sr_profiler : public sr_singleton<sr_profiler> {
        std::map<std::string, sr_clock> clocks;
        std::stack<std::string> id_stack;

        // 开启计时
        void begin(std::string sid) {
            id_stack.push(sid);
            if (clocks.find(sid) == clocks.end()) {
                clocks.insert(std::pair<std::string, sr_clock>(sid, sr_clock(sid)));
            } else {
                clocks.at(sid).p_clock = clock();
            }
        }

        // 结束计时
        double end() {
            std::string sid = id_stack.top();
            id_stack.pop();
            double delta_time = (double) (clock() - clocks.at(sid).p_clock) / CLOCKS_PER_SEC;
            clocks.at(sid).cnt_timer += delta_time;
            return delta_time;
        }

        void export_log() {
            for (auto &clock : clocks) {
                std::cout << clock.first << " " << clock.second.cnt_timer * 1000 / frame_from_start << " ms" << std::endl;
            }
        }
    };
}

#endif //SHEEPRENDER_SR_PROFILER_H
